package com.lhy.backend.components.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lhy.backend.domain.entity.user.*;
import com.lhy.backend.mapper.user.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 实现方法，在此方法中根据用户名查询用户
     * 账号：用户名、手机号、邮箱，通过正则表达式判断账号类型
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账号查询用户
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if (ObjectUtils.isNotNull(sysUser)) {
            //获取角色id
            LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
            sysUserRoleWrapper.eq(SysUserRole::getUserId, sysUser.getId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleWrapper);
            //获取角色
            LambdaQueryWrapper<SysRole> sysRoleWrapper = new LambdaQueryWrapper<>();
            List<Long> sysRoleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysRoleWrapper.in(SysRole::getRoleId, sysRoleIds);
            Set<SysRole> roleList = new HashSet<>(sysRoleMapper.selectList(sysRoleWrapper));
            sysUser.setRoleList(roleList);
            //获取menuId
            LambdaQueryWrapper<SysRoleMenu> sysRoleMenuWrapper = new LambdaQueryWrapper<>();
            sysRoleMenuWrapper.in(SysRoleMenu::getRoleId, sysRoleIds);
            List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(sysRoleMenuWrapper);
            List<Long> sysMenuIds = sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
            //根据角色查询权限 menu
            LambdaQueryWrapper<SysMenu> sysMenuWrapper = new LambdaQueryWrapper<>();
            sysMenuWrapper.in(SysMenu::getId, sysMenuIds);
            List<SysMenu> sysMenus = sysMenuMapper.selectList(sysMenuWrapper);
            Set<String> perms = sysMenus.stream().map(SysMenu::getPerms).collect(Collectors.toSet());
            sysUser.setPerms(perms);
        }
        return sysUser;
    }
}
